package com.rongmai.web.bo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rongmai.db.dto.CompanyDTO;
import com.rongmai.db.dto.CompanyFeatureDTO;
import com.rongmai.db.dto.DepartmentDTO;
import com.rongmai.db.enums.UserRoleEnum;
import com.rongmai.db.mapper.*;
import com.rongmai.db.model.*;
import com.rongmai.db.vo.Page;
import com.rongmai.db.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CompanyBo {

    @Resource
    private LabelBo labelBo;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private FinanceProductMapper financeProductMapper;
    @Resource
    private FinanceProductAuditMapper financeProductAuditMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private DepartmentAuditMapper departmentAuditMapper;
    @Resource
    private SubmitProductMapper submitProductMapper;
    @Resource
    private SubmitProductAuditMapper submitProductAuditMapper;
    @Resource
    private CompanyAuditMapper companyAuditMapper;
    @Resource
    private UserBo userBo;
    @Resource
    private CompanyRoleBo companyRoleBo;

    public Company get(String name, String role) {
        return companyMapper.getByName(name, role);
    }


    public CompanyDTO myCompany(Integer userId) {
        UserVo userVo = userBo.detail(userId);
        if (userVo == null) return null;
        String departmentId = userVo.getDepartment();
        Company company = companyMapper.getByName(userVo.getCompanyName(), userVo.getRole());
        if (company == null) return null;
        CompanyDTO companyDTO = new CompanyDTO();
        BeanUtils.copyProperties(company, companyDTO);
        companyDTO.setModelLabelNames(getLabelNames(company.getModelLabelIds()));
        companyDTO.setIndustryLabelNames(getLabelNames(company.getIndustryLabelIds()));
        companyDTO.setProductLabelNames(getLabelNames(company.getProductLabelIds()));
        companyDTO.setCompanyFeatures(getFeatureDto(company.getFeatureJson()));
        Department department = departmentMapper.queryByCompanyIdAndLabelId(company.getId(), Integer.valueOf(departmentId));
        if (department != null) {
            DepartmentDTO departmentDTO = new DepartmentDTO();
            BeanUtils.copyProperties(department, departmentDTO);

            List<FinanceProduct> financeProducts = financeProductMapper.queryByDepartmentId(department.getId());
            departmentDTO.setFinanceProducts(financeProducts);
            List<SubmitProduct> submitProducts = submitProductMapper.queryByDepartmentId(department.getId());
            departmentDTO.setSubmitProducts(submitProducts);

            companyDTO.setDepartments(Arrays.asList(departmentDTO));
        }

        return companyDTO;
    }

    private List<CompanyFeatureDTO> getFeatureDto(String feature) {
        try {
            return (List<CompanyFeatureDTO>) JSONArray.parse(feature);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Collections.emptyList();
    }

    public static void main(String[] args) {
        Map<String, List<CompanyFeatureDTO>> gqtrFeature = CompanyFutureBo.getGQTRFeature();
        List<CompanyFeatureDTO> feature = gqtrFeature.get(UserRoleEnum.INVEST.name());
        String jsonString = JSON.toJSONString(feature);
        List<CompanyFeatureDTO> featureDto = new CompanyBo().getFeatureDto(jsonString);
        System.out.println(featureDto);

    }

    public CompanyDTO detail(Integer companyId) {
        Company company = companyMapper.getById(companyId);
        return convertToDTO(company);
    }

    public void edit(CompanyDTO companyDTO, User currentUser) {
        Company company = get(companyDTO.getName(), companyDTO.getRole());
        if (company == null) {
            log.error("公司信息不存在，请检查");
            return;
        }
        BeanUtils.copyProperties(companyDTO, company);
        company.setFeatureJson(JSON.toJSONString(companyDTO.getCompanyFeatures()));
        companyMapper.update(company);
        Integer companyId = company.getId();

        if (!StringUtils.isEmpty(companyDTO.getDepartments())) {
            StringBuilder departmentLabelIds = new StringBuilder();
            for (DepartmentDTO departmentDTO : companyDTO.getDepartments()) {
                departmentMapper.deleteByCompanyId(companyId);

                Department departmentAudit = new Department();
                BeanUtils.copyProperties(departmentDTO, departmentAudit);
                departmentAudit.setCompanyId(companyId);
                departmentMapper.insert(departmentAudit);
                departmentLabelIds.append(departmentDTO.getLabelId());

                Integer departmentAuditId = departmentAudit.getId();

                if (!StringUtils.isEmpty(departmentDTO.getFinanceProducts())) {
                    financeProductMapper.deleteByCompanyIdAndDepartmentId(companyId, departmentAuditId);
                    for (FinanceProduct financeProduct : departmentDTO.getFinanceProducts()) {

                        FinanceProduct financeProductAudit = new FinanceProduct();
                        BeanUtils.copyProperties(financeProduct, financeProductAudit);
                        financeProductAudit.setCompanyId(companyId);
                        financeProductAudit.setDepartmentId(departmentAuditId);
                        financeProductAudit.setCreateTime(new Date());
                        financeProductMapper.insert(financeProductAudit);
                    }

                }
                if (!StringUtils.isEmpty(departmentDTO.getSubmitProducts())) {
                    submitProductMapper.deleteByCompanyIdAndDepartmentId(companyId, departmentAuditId);

                    for (SubmitProduct submitProduct : departmentDTO.getSubmitProducts()) {
                        SubmitProduct submitProductAudit = new SubmitProduct();
                        BeanUtils.copyProperties(submitProduct, submitProductAudit);
                        submitProductAudit.setCompanyId(companyId);
                        submitProductAudit.setDepartmentId(departmentAuditId);
                        submitProductAudit.setCreateTime(new Date());
                        submitProductMapper.insert(submitProductAudit);
                    }
                }

            }
        }

    }


//    public Page<CompanyDTO> pageQuery(CompanyDTO companyDTO, String labelCode) {
//        List<LabelDto> labels = labelBo.getLabelDtoByCode(labelCode, true);
//        companyDTO.setQueryKeyIds(labels.stream().map(LabelDto::getId).collect(Collectors.toList()));
//        return pageQuery(companyDTO);
//    }

    public Page<CompanyDTO> pageQuery(CompanyDTO companyDTO) {

        String queryKey = companyDTO.getQueryKey();
        List<Label> labels = labelBo.queryByName(queryKey);
        companyDTO.setQueryKeyIds(labels.stream().map(Label::getId).collect(Collectors.toList()));
        if (companyDTO.getPageNo() != 0) {
            companyDTO.setPageNo(companyDTO.getPageNo() - 1);
        }
        if (companyDTO.getPageSize() == 0) {
            companyDTO.setPageSize(10);
        }
        Set<Integer> companyIds = new HashSet<>();
        //查询产品关联的公司
        if (!StringUtils.isEmpty(companyDTO.getQueryKey())) {
            List<FinanceProduct> financeProducts = financeProductMapper.queryByProductName(companyDTO.getQueryKey());
            Set<Integer> proCompanyIds = financeProducts.stream().map(FinanceProduct::getCompanyId).collect(Collectors.toSet());
            companyIds.addAll(proCompanyIds);
        }
        //查询职位关联的公司
        if (!StringUtils.isEmpty(companyDTO.getQueryKey())) {
            List<Department> departments = departmentMapper.queryByDepartmentName(companyDTO.getQueryKey());
            Set<Integer> collected = departments.stream().map(Department::getCompanyId).collect(Collectors.toSet());
            companyIds.addAll(collected);
        }
        //查询职位labelId关联的公司
        if (!StringUtils.isEmpty(companyDTO.getTitleLabelId())) {
            List<Department> departments = departmentMapper.queryByLabelId(Integer.valueOf(companyDTO.getTitleLabelId()));
            Set<Integer> collected = departments.stream().map(Department::getCompanyId).collect(Collectors.toSet());
            companyIds.addAll(collected);
        }

        companyDTO.setCompanyIds(companyIds);
        List<Company> companyList = companyMapper.page(companyDTO);
        List<CompanyDTO> companyDTOList = new ArrayList<>();
        companyList.forEach(company -> {
            companyDTOList.add(convertToDTO(company));
        });
        Page<CompanyDTO> result = new Page<>();
        result.setList(companyDTOList);
        result.setTotal(companyMapper.count(companyDTO));
        return result;
    }

    private CompanyDTO convertToDTO(Company company) {
        if (company == null) return null;
        CompanyDTO temp = new CompanyDTO();
        BeanUtils.copyProperties(company, temp);
        temp.setModelLabelNames(getLabelNames(company.getModelLabelIds()));
        temp.setIndustryLabelNames(getLabelNames(company.getIndustryLabelIds()));
        temp.setProductLabelNames(getLabelNames(company.getProductLabelIds()));
        List<Department> departments = departmentMapper.queryByCompanyId(company.getId());
        if (!CollectionUtils.isEmpty(departments)) {
            List<DepartmentDTO> departmentDTOS = new ArrayList<>();
            for (Department department : departments) {
                DepartmentDTO departmentDTO = new DepartmentDTO();
                BeanUtils.copyProperties(department, departmentDTO);

                List<FinanceProduct> financeProducts = financeProductMapper.queryByDepartmentId(department.getId());
                departmentDTO.setFinanceProducts(financeProducts);

                List<SubmitProduct> submitProducts = submitProductMapper.queryByDepartmentId(department.getId());
                departmentDTO.setSubmitProducts(submitProducts);

                departmentDTOS.add(departmentDTO);
            }
            temp.setDepartments(departmentDTOS);
        }
        temp.setCompanyFeatures(getFeatureDto(company.getFeatureJson()));
        return temp;
    }

    private List<String> getLabelNames(String modelLabelIds) {
        if (StringUtils.isEmpty(modelLabelIds)) {
            return null;
        }
        return labelBo.getNameListByIds(modelLabelIds);
    }

}
